<?php
/**
 * 《分机信息》实现类
 *
 * @author 孙晓晔
 * @version $Id: Exten.class.php 1035 2010-03-26 05:24:59Z sunxy $
 */

require_once(dirname(__FILE__) . '/EmpUtil.class.php');

class Exten extends EmpUtil {
	public $tbl = Constant::tbl_emp_exten;

	public $recording = array(
		'-' => '请选择',
		'Always' => 'Always',
		'Never' => 'Never',	
		'Adhoc' => 'Adhoc',		
	);
	
	public $status = array(
		'-' => '请选择',
		'1' => '有效',
		'2' => '无效',
	
		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'exten' => '分机',
		'IP' => 'IP',
		'emp' => '员工',
		'`out`' => '分机权限',

		'1' => '创建时间',
		'2' => '更新时间',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/03/06 11:35:48 $';
		$request['revision'] = '$Revision: 1.2 $';
			
		parent::__construct($request);
	}

	/**
	 * 预处理
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function pretreat($controller) {
		parent::pretreat($controller);

		$controller->assign_by_ref('recording_option', $this->recording);

		$controller->assign_by_ref('service_option', $this->service);
	}

	/**
	 * 首页
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function layout($controller, $request) {

		$controller->display($request, 'priv');
		return true;
	}

	/**
	 * 查找
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);
			
		$controller->display($request, 'emp/exten/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == '`join`') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['join'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}
	
		$emp = $_SESSION['id'];
	
		$p = array('1'=>'206', '2'=>'207', '3'=>'208');
	
		$a = $this->_audit_office($p);
		if (count($a) > 0) {
			$office = implode(",", $a);
				
			return sprintf(" visible = 1 AND (office in (%s) OR oper = '%s')", $office, $emp);
		}
	
		return sprintf(" visible = 1 AND (emp = '%s' OR oper = '%s')", $emp, $emp);
	}

	function _where($request) {
		$name_s = $request['name_s'];
		
		$exten_s = $request['exten_s'];
		$cf_s = $request['cf_s'];

		$out_s = $request['out_s'];

		$record_in_s = $request['record_in_s'];
		$record_out_s = $request['record_out_s'];

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}
		
		if (!empty($name_s)) {
			$where .= sprintf(" AND (content LIKE '%s' OR ua LIKE '%s')", "%" . $name_s . "%", "%" . $name_s . "%");
		}

		if (!empty($exten_s)) {
			$where .= " AND exten like '" . $exten_s . "%'";
		}

		if (!empty($cf_s)) {
			$where .= " AND cf = '" . $cf_s . "'";
		}

		if (!empty($out_s) && $out_s <> '-') {
			$where .= " AND `out` = '" . $out_s . "'";
		}

		if (!empty($record_in_s) && $record_in_s <> '-') {
			$where .= " AND record_in = '" . $record_in_s . "'";
		}

		if (!empty($record_out_s) && $record_out_s <> '-') {
			$where .= " AND record_out = '" . $record_out_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {

			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'emp/exten/list');
		return true;
	}
	
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'emp/exten/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		$row['cf_t'] = $this->_cf_name($row['cf']);
		$row['cfu_t'] = $this->_cf_name($row['cfu']);
		$row['cfb_t'] = $this->_cf_name($row['cfb']);
		
		if (empty($row['t1'])) {
			$row['t1'] = "08:00";
		}
		
		if (empty($row['t2'])) {
			$row['t2'] = "20:00";
		}
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function _view_exten($exten) {		
		$row = Common::x($this->tbl, 'exten', $exten);
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function _out($exten) {
		
		if ($row = $this->_view_exten($exten)) {
			return $row['out'];
		}
	
		return false;
	}
	
	function _exist($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE emp = '%s' ORDER BY orderby";
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			return $row;
		}
	
		return false;
	}
	
	function _exten_out($id, $exten, $out) {
		if (empty($exten)) {
			return false;
		}
	
		$db = newdb($this->dsn_w);
	
		$fmt = "SELECT * FROM %s WHERE exten = '%s'";
		$sql = sprintf($fmt, $this->tbl, $exten);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			$fmt = "UPDATE %s SET `out` = '%s' WHERE emp = '%s' and exten = '%s'";
		} else {
			$fmt = "INSERT INTO %s(`out`, emp, exten, createtime, modifytime) VALUES('%s', '%s', '%s', now(), now())";
		}
		$sql = sprintf($fmt, $this->tbl, $out, $id, $exten);
		$db->query($sql);
	
		clean($this->tbl . "_id_" . $id);
		$row = $this->id($this->tbl, $id);
	
		$am = $this->am($exten);
		if (!$am) {
			return false;
		}
	
		if ($row['out'] == $out) {
			return false;
		}
	
		$am->database_put('OUT', $exten, $out);
	}

	function _cf_name($exten) {
		if (empty($exten)) {
			return '';
		}

		$row = $this->_exten($exten);
		if (empty($row['emp'])) {
			return $row['exten'];
		}

		return sprintf("%s [%s]", Name::emp($row['emp']), $row['exten']);
	}

	function _exten($exten) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE exten = '%s'";
		$sql = sprintf($fmt, $this->tbl, $exten);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			return $row;
		}

		return false;
	}
	
	function move($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
	
	function _timeout($exten) {
		$ret = 1200;
		if (!preg_match("/^(2|6|8)\d{3}$/i", $exten)) {
			return $ret;
		}
		
		if ($row = $this->_exten($exten)) {
			return $row['timeout'];
		}
		
		return $ret;
	}

	function _cf($exten) {
		$key = "cf_" . $exten;
		debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (preg_match("/\d{4,}/", $ret)) {
				debug('ret ...' . $key);
				return $ret;
			}
		}

		if (preg_match("/^6\d{3}/i", $exten)) {
			$am = astman('ns');
		} else if (preg_match("/^8\d{3}/i", $exten)) {
			$am = astman('sj');
		} else if (preg_match("/^2\d{3}/i", $exten)) {
			$am = astman('fy');
		} else {
			return true;
		}

		$ret = $am->database_get('CF', $exten);
		$am->disconnect();

		if (empty($ret)) {
			$ret = '0000';
		}

		if (is_object($mc)) {
			$mc->set($key, $ret, 0, _strtotime("1 hour"));
		}

		return $ret;
	}

	function _recording($exten) {
		$key = "recording_" . $exten;
		debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				debug('recording ret ...' . $key);
				return $ret;
			}
		}

		if (preg_match("/^6\d{3}/i", $exten)) {
			$am = astman('ns');
		} else if (preg_match("/^8\d{3}/i", $exten)) {
			$am = astman('sj');
		} else if (preg_match("/^2\d{3}/i", $exten)) {
			$am = astman('fy');
		} else {
			return true;
		}

		$s = $am->database_get('AMPUSER', $exten . "/recording");
		$am->disconnect();

		$ret['exten'] = $exten;

		$recording = explode("|", $s);
		$ret['out'] = substr($recording[0], 4);
		$ret['in'] = substr($recording[1], 3);

		if (is_object($mc)) {
			$mc->set($key, $ret, 0, _strtotime("1 hour"));
		}

		return $ret;
	}

	function sj($controller, $request) {		
		$request['ast'] = 'sj';
		
		$this->_update($controller, $request);
	}
		
	function ns($controller, $request) {		
		$request['ast'] = 'ns';
		
		$this->_update($controller, $request);
	}
	
	function qx($controller, $request) {
		$request['ast'] = 'qx';
	
		$this->_update($controller, $request);
	}
		
	function _update($controller, $request) {		
		$am = astman($request['ast']);
		$ret = $am->Command('sip show peers');

		$data = $ret['data'];
		// echo $data;

		$aa = preg_split("/[\\n]+/i", $data);

		$db = newdb($this->dsn_w);
		while (list($k, $v) = each($aa)) {
			$buf = trim($v);
			if (strlen($buf) < 5) {
				continue;
			}

			if (!preg_match("/^\d/", $buf)) {
				continue;
			}

			$a = preg_split("/[\\s,]+/", $buf);
			
			$b = preg_split("/[\/]+/", $a[0]);
			// print_r($a);
			
			$user = $b[0];
			$host = $a[1];
			$port = $a[5];

			$status = '2';
			if (count($a) > 6 && $a[6] == 'OK') {
				$status = '1';
			}

			if (!preg_match("/^\d/", $host)) {
				continue;
			}

			$ret = $am->Command('sip show peer ' . $user);
			$data = $ret['data'];

			$ua = $this->useragent($data);

			$fmt = "UPDATE %s SET ip = '%s', ua = '%s' WHERE exten = '%s'";
			$sql = sprintf($fmt, $this->tbl, $host, $ua, $user);
			echo $sql . "\n";
			$db->query($sql);
		}

		$am->disconnect();
		
		logdate($controller, $request);
		return true;
	}	
	
	function useragent($data) {
		$aa = preg_split("/[\\n]+/i", $data);
		while (list($k, $v) = each($aa)) {
			$buf = trim($v);
			if (strlen($buf) < 5) {
				continue;
			}

			if (preg_match("/^Useragent/", $buf)) {
				$pos = strpos($buf, ":");
				return trim(substr($buf, $pos + 1));
			}
		}

		return '';
	}
	
	function u($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$a = $this->_peer($row['exten']);

			$fmt = "UPDATE %s SET ip = '%s', ua = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $a['ip'], $a['ua'], $a['status'], $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}

		logdate($controller, $request);
		return true;
	}
	
	function t($controller, $request) {
		$a = $this->_peer("6026");
		// $a = $this->_peer("6595");
		// $a = $this->_peer("6005");
		
		print_r($a);

		logdate($controller, $request);
		return true;
	}
	
	function _peer($exten) {
		$am = $this->_ast($exten);
		
		$ret = $am->Command('sip show peer ' . $exten);
		$data = $ret['data'];
		// echo $data;		

		$ret = array('ip'=>'', 'ua'=>'', 'status'=>2);
		$a = $this->_toarray($data);
		if (count($a) < 2) {
			return $ret;
		}
		
		if (preg_match("/^OK/i", $a['Status'])) {
			$ret['status'] = 1;
		} else {
			return $ret;
		}
		
		$ret['ip'] = $this->_ip($a['Addr->IP']);		
		$ret['ua'] = $a['Useragent'];
		
		return $ret;
	}
	
	function _toarray($data) {
		$ret = array();
		$aa = preg_split("/[\\n]+/i", $data);
		while (list($k, $buf) = each($aa)) {
			
			$pos = strpos($buf, ":");
			if ($pos < 1) {
				continue;
			}
			
			$k = trim(substr($buf, 0, $pos));
			$v = trim(substr($buf, $pos + 1));
			$ret[$k] = $v;
		}

		return $ret;
	}
	
	function _ip($buf) {
		$pos = strpos($buf, ":");
		if ($pos < 1) {
			return '';
		}
		
		return trim(substr($buf, 0, $pos));
	}
	
	function ns_sip($controller, $request) {
		$am = astman('ns');

		$am->Events("off");
		$am->add_event_handler("Status", "ast_status");
		
		while(true) {			 
			echo ".";
			$am->send_request('Status');
			sleep(5);			
		}

		$am->disconnect();
		logdate($controller, $request);
		return true;
	}
	
	function sj_sip($controller, $request) {
		
		$i = 360;
		while($i > 0) {
			if ($i == 360) {
				$am = astman('sj');

				$am->Events("off");
				$am->add_event_handler("Status", "ast_status");
			}
			
			echo sprintf("%s\n", $i);
			$am->send_request('Status');
			sleep(5);

			$i--;
			if ($i == 0) {
				$am->disconnect();
				$i = 360;
			}
		}
				
		logdate($controller, $request);
		return true;
	}

	function clean($controller, $request) {
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->delete('peers');
		}
	}

	function insert($exten) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE exten = '%s'";
		$sql = sprintf($fmt, $this->tbl, $exten);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return false;
		}

		$fmt = "INSERT INTO %s(exten, createtime, modifytime) VALUES('%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $exten);
		$db->query($sql);
	}

	function sync($controller, $request) {
		$am = astman('sj');

		$db = newdb('sunxy');
		$fmt = "SELECT * FROM %s a, %s b WHERE a.id = b.emp AND a.status = '1' and b.exten like '%s'";
		$sql = sprintf($fmt, Constant::tbl_emp, $this->tbl, "8%");
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// $am->database_put('OUT', $row['exten'], $row['out']);
			// $am->database_put('CO', $row['exten'], $row['co']);
			$am->database_put('CF', $row['exten'], $row['cf']);
			echo ".";
		}

		$am->disconnect();

		logdate($controller, $request);
		return true;
	}

	function z_cf($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$exten = $row['exten'];

			$this->_sync_cf($exten);

			if (empty($cf)) {
				echo ".";
				continue;
			}

			$fmt = "UPDATE %s SET cf = '%s' WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $cf, $row['id']);
			$db->query($sql);

			// $am->database_put('OUT', $row['exten'], $row['out']);
			echo $exten . " = " . $cf . "\n";
		}

		logdate($controller, $request);
		return true;
	}
	
	function z_cfu($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE status = 1";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$exten = $row['exten'];
			$cfu = $row['cfu'];
			if (empty($cfu)) {
				echo "S";
				continue;
			}
			
			echo $exten . " = " . $cfu . "\n";

			$am = $this->_ast($exten);
			$am->database_put('CFU', $row['exten'], $cfu);
			$am->disconnect();	
		}

		logdate($controller, $request);
		return true;
	}
	
	function z_sync($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE status = 1";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$exten = $row['exten'];
			$am = $this->_ast($exten);
			
			$cf = $row['cf'];
			if (empty($cf)) {
				$am->database_del('CF', $exten);
			} else {
				$am->database_put('CF', $exten, $cf);
			}
			
			$cfu = $row['cfu'];
			if (empty($cfu)) {
				$am->database_del('CFU', $exten);
			} else {
				$am->database_put('CFU', $exten, $cfu);
			}
			
			$cfb = $row['cfb'];
			if (empty($cfu)) {
				$am->database_del('CFB', $exten);
			} else {
				$am->database_put('CFB', $exten, $cfb);
			}
			
			$dnd = $row['dnd'];
			if (empty($dnd) || $dnd == 'NO') {
				$am->database_del('DND', $exten);
			} else {
				$am->database_put('DND', $exten, $dnd);
			}
			
			$record_in = $row['record_in'];
			$record_out = $row['record_out'];
			
			$this->_setting_record($am, $exten, $record_in, $record_out);
				
			// echo $exten . " = " . $cfu . "\n";
			echo ".";			
			
			$am->disconnect();
		}
	
		logdate($controller, $request);
		return true;
	}
	
	function _ast($exten) {
		if (preg_match("/^2\d{3}/i", $exten)) {
			return astman("qx");
		}

		if (preg_match("/^6\d{3}/i", $exten)) {
			return astman("ns");
		}

		if (preg_match("/^8\d{3}/i", $exten)) {
			return astman("sj");
		}
		
		return false;
	}
	
	function _sync_cf($exten) {
		$am = $this->_ast($exten);
		
		$cf = $am->database_get('CF', $exten);
		
		$am->disconnect();
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		require_once 'Emp.class.php';
		$emp = new Emp();
		$controller->assign_by_ref('emp', $emp->_view($id));

		$this->_my_emp($controller, $id);

		$controller->display($request, 'emp/exten/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);

		$emp = $request['id'];
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);

		$exten = $request['exten'];

		$record_in = $request['record_in'];
		$record_out = $request['record_out'];

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, dept, emp, exten, record_in, record_out, oper, createtime, modifytime) ";
		$fmt .= "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $exten, $record_in, $record_out, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);

		$this->add($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function copy($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'emp/exten/copy');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function copyPost($controller, $request) {
		$this->pretreat($controller);

		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);

		$exten = $request['exten'];

		$record_in = $request['record_in'];
		$record_out = $request['record_out'];

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(office, dept, emp, exten, record_in, record_out, oper, createtime, modifytime) ";
		$fmt .= "VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $exten, $record_in, $record_out, $_SESSION['id']);
		// debug($sql);
		$db->query($sql);
		
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'emp/exten/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		$row = $this->id($this->tbl, $id);

		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$name = addslashes($request['name']);
		$exten = $request['exten'];
		
		$timeout = $request['timeout'];
		$cf = $request['cf'];

		$record_in = $request['record_in'];
		$record_out = $request['record_out'];
		
		$cf = $request['cf'];
		$cfu = $request['cfu'];
		$cfb = $request['cfb'];
		$dnd = $request['dnd'];

		$am = $this->am($row['exten']);
		$this->_edit_cf($am, $row, $cf);
		// $this->_edit_out($am, $row, $out);
		$this->_edit_record($am, $row, $record_in, $record_out);
		
		$this->_setting_cf($am, $row, $cf);
		$this->_setting_cfu($am, $row, $cfu);
		$this->_setting_cfb($am, $row, $cfb);
		$this->_setting_dnd($am, $row, $dnd);

		$this->am_close($am);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET office = '%s', dept = '%s', emp = '%s', name = '%s', exten = '%s', timeout = '%s', record_in = '%s', record_out = '%s', cf = '%s', cfu = '%s', cfb = '%s', dnd = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $dept, $emp, $name, $exten, $timeout, $record_in, $record_out, $cf, $cfu, $cfb, $dnd, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _setting_cf($am, $row, $val) {
		if (!$am) {
			return false;
		}
	
		if ($row['cf'] == $val) {
			return false;
		}
	
		if (empty($val)) {
			return $am->database_del('CF', $row['exten']);
		}
	
		$am->database_put('CF', $row['exten'], $val);
	}
	
	function _setting_cfb($am, $row, $val) {
		if (!$am) {
			return false;
		}
	
		if ($row['cfb'] == $val) {
			return false;
		}
	
		if (empty($val)) {
			return $am->database_del('CFB', $row['exten']);
		}
	
		$am->database_put('CFB', $row['exten'], $val);
	}
	
	function _setting_cfu($am, $row, $val) {
		if (!$am) {
			return false;
		}
	
		if ($row['cfu'] == $val) {
			return false;
		}
	
		if (empty($val)) {
			return $am->database_del('CFU', $row['exten']);
		}
	
		$am->database_put('CFU', $row['exten'], $val);
	}
	
	function _setting_dnd($am, $row, $val) {
		if (!$am) {
			return false;
		}
	
		if ($row['dnd'] == $val) {
			return false;
		}
	
		if (empty($val) || $val == 'NO') {
			return $am->database_del('DND', $row['exten']);
		}
	
		$am->database_put('DND', $row['exten'], $val);
	}
	
	function _setting_record($am, $exten, $in, $out) {
		if (!$am) {
			return false;
		}
	
		if (empty($in) || $in == '-') {
			$in = "Adhoc";
		}
	
		if (empty($out) || $out == '-') {
			$out = "Adhoc";
		}
	
		$fmt = "out=%s|in=%s";
		$cmd = sprintf($fmt, $out, $in);
	
		$am->database_put('AMPUSER', $exten . '/recording', $cmd);
		
		$db = $this->am_sql($exten);
		$fmt = "UPDATE %s SET recording = '%s' WHERE extension = '%s'";
		$sql = sprintf($fmt, "asterisk.users", $cmd, $exten);
		echo $sql . "\n";
		$db->query($sql);
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function co($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'emp/exten/co');
		return true;
	}
	
	function _co($co) {
		$a = json_decode($co);		
		if (!$a || $a == NULL) {
			debug("week is NULL");
			return 0;
		}
		
		$ret = 0;
		while (list($k, $v) = each($a)) {
			$ret |= pow(2, intval($v));
		}
		
		return $ret;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function coPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		$row = $this->id($this->tbl, $id);

		$emp = $this->_input($request['emp']);

		$exten = $request['exten'];
		$cf = $request['cf'];
		
		$t1 = $request['t1'];
		$t2 = $request['t2'];
		
		$co = $this->_co($request['co']);		
		
		$am = $this->am($row['exten']);
		
		$this->_edit_cf($am, $row, $cf);
		$this->_edit_co($am, $row, $co);
		$this->_edit_time($am, $row, $t1, $t2);
		
		$this->am_close($am);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s', exten = '%s', cf = '%s', `co` = '%s', t1 = '%s', t2 = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $emp, $exten, $cf, $co, $t1, $t2, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function _edit_cf($am, $row, $cf) {
		if (!$am) {
			return false;
		}

		if ($row['cf'] == $cf) {
			return false;
		}

		if (empty($cf)) {
			return $am->database_del('CF', $row['exten']);
		}

		$am->database_put('CF', $row['exten'], $cf);
	}
	
	function _edit_co($am, $row, $co) {
		if (!$am) {
			return false;
		}

		if ($row['co'] == $co) {
			return false;
		}

		$am->database_put('CO', $row['exten'], $co);
	}
	
	function _edit_time($am, $row, $t1, $t2) {
		if (!$am) {
			return false;
		}

		if ($row['t1'] == $t1 && $row['t2'] == $t2) {
			return false;
		}

		if (empty($t1) || $t1 == '-') {
			return false;
		}

		if (empty($t2) || $t2 == '-') {
			return false;
		}

		$fmt = "from=%s|to=%s";
		$cmd = sprintf($fmt, $t1, $t2);

		$am->database_put('time', $row['exten'], $cmd);
	}

	function _edit_record($am, $row, $in, $out) {
		if (!$am) {
			return false;
		}

		if ($row['record_in'] == $in && $row['record_out'] == $out) {
			return false;
		}

		if (empty($in) || $in == '-') {
			$in = "Adhoc";
		}

		if (empty($out) || $out == '-') {
			$out = "Adhoc";
		}

		$fmt = "out=%s|in=%s";
		$cmd = sprintf($fmt, $out, $in);

		$am->database_put('AMPUSER', $row['exten'] . '/recording', $cmd);
		
		$db = $this->am_sql($row['exten']);
		$fmt = "UPDATE %s SET recording = '%s' WHERE extension = '%s'";
		$sql = sprintf($fmt, "asterisk.users", $cmd, $row['exten']);
		// echo $sql . "\n";
		$db->query($sql);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}

			$fmt = "DELETE FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $id);
			// debug($sql);
			$db->query($sql);
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax($controller, $request) {
		$q = $request['q'];
		if (preg_match("/^(\d+)$/i", $q)) {
			$data = $this->_ajax($request);
		} else {
			$data = $this->_ajax_zjm($request);
		}

		echo json_encode($data);
	}

	function _ajax($request) {
		$q = $request['q'];
		
		$key = sprintf("%s_%s_%s", $this->zjm, $this->prefix, $zjm);
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}
		
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE status = '1' AND exten LIKE '%s' LIMIT %s";
		$sql = sprintf($fmt, $this->tbl, $q . "%", $n);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			/*
			$a = $this->_emp($row['emp']);

			if (is_array($a)) {
				$row['name'] = $a['name'];
				$row['dept_t'] = $a['dept_t'];
			}*/

			$ret[] = $row;
		}
		
		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}
	/*

	function _emp($id) {
		$row = $this->id(Constant::tbl_emp, $id);

		$ret['name'] = $row['name'];
		$ret['dept_t'] = Name::dept($row['dept']);

		return $ret;
	}*/

	function _ajax_zjm($request) {
		$zjm = $request['q'];
		
		$key = sprintf("%s_%s_%s", $this->zjm, $this->prefix, $zjm);
		// debug($key);
		$mc = memcache("root");
		if (is_object($mc)) {
			$ret = $mc->get($key);
			if (is_array($ret)) {
				return $ret;
			}
		}
		
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT a.name emp_t, a.dept, b.exten FROM %s a, %s b WHERE a.id = b.emp AND b.status = '1' AND a.zjm LIKE '%s' LIMIT %s";
		$sql = sprintf($fmt, Constant::tbl_emp, $this->tbl, $zjm . "%", $n);
		debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row['dept_t'] = Name::dept($row['dept']);

			$ret[] = $row;
		}
		
		if (is_object($mc) && count($ret) > 0) {
			$mc->set($key, $ret, 0, _strtotime("1 day"));
		}

		return $ret;
	}
	
	function freepbx_ns($controller, $request) {
		$db = newdb('sunxy');
		$fmt = "SELECT a.* FROM %s a, %s b WHERE a.emp = b.id and a.exten like '%s' and b.status = 1";
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_emp, '6%');
		echo $sql;
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// print_r($row);
			$this->_freepbx_add($row['exten']);
			// $this->_freepbx_del($row['exten']);			
		}		
		
		return true;
	}
	
	function freepbx_sj($controller, $request) {
		$db = newdb('sunxy');
		$fmt = "SELECT a.* FROM %s a, %s b WHERE a.emp = b.id and a.exten like '%s' and b.status = 1";
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_emp, '8%');
		echo $sql;
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			// print_r($row);
			$this->_freepbx_add($row['exten']);
			// $this->_freepbx_del($row['exten']);			
		}		
		
		return true;
	}

	function c($controller, $request) {
		// $this->_freepbx_add('6595');
		// $this->_freepbx_add('6001');
		// $this->_freepbx_add('6002');
		// $this->_freepbx_add('6006');
		// $this->_freepbx_add('8054');
		// $this->_freepbx_add('2001');
		// $this->_freepbx_add('2002');
		$this->_freepbx_add('8056');
		
		// $this->_freepbx_del('6595');
	}
	
	function freepbx($controller, $request) {
		$exten = '8008';
		
		$a = array('8001','8002','8003','8004','8005', '8006', '8007');
		foreach ($a as $k => $v) {
			// $this->_freepbx_del($exten);
			$this->_freepbx_del($v);
		}
		// $this->_freepbx_add($exten);
	}
	
	function _freepbx_del($exten) {
		$var = array(			
			'action' => 'del',
			'display' => 'extensions',
			'type' => 'setup',
			'extdisplay' => $exten
			);
		
		$fields_string = '';
		foreach($var as $key=>$value) {
			$fields_string .= $key . '=' . urlencode($value) .'&'; 
		}
		
		$fields_string = rtrim($fields_string, '&') ; 
		
		echo $fields_string;
			
		$url = "http://192.168.2.11/admin/config.php";
		
		$this->_curl_post($url, $fields_string);
	}
	
	function _freepbx_add($exten) {
		$var = array(
			'Submit' => 'Submit',
			'action' => 'add',
			'action' => 'add',
			'call_screen' => '0',
			'callwaiting' => 'enabled',
			'cid_masquerade' => '',
			'devinfo_accountcode' => '',
			'devinfo_allow' => '',
			'devinfo_callgroup' => '',
			'devinfo_canreinvite' => 'no',
			// 'devinfo_context' => 'from-internal',
			'devinfo_context' => 'tt',
			'devinfo_deny' => '0.0.0.0/0.0.0.0',
			'devinfo_dial' => '',
			'devinfo_disallow' => '',
			'devinfo_dtmfmode' => 'rfc2833',
			'devinfo_host' => 'dynamic',
			'devinfo_mailbox' => '',
			'devinfo_nat' => 'yes',
			'devinfo_permit' => '0.0.0.0/0.0.0.0',
			'devinfo_pickupgroup' => '',
			'devinfo_port' => '5060',
			'devinfo_qualify' => 'yes',
			'devinfo_secret' => '1111',
			'devinfo_secret_origional' => '',
			'devinfo_type' => 'friend',
			'devinfo_vmexten' => '',
			'dictemail' => '',
			'dictenabled' => 'disabled',
			'dictformat' => 'ogg',
			'display' => 'extensions',
			'emergency_cid' => '',
			'extdisplay' => '',
			'extension' => $exten,
			'hardware' => 'generic',
			'langcode' => '',
			'name' => $exten,
			'newdid_name' => '',
			'newdidcid' => '',
			'outboundcid' => '',
			'pinless' => 'disabled',
			'record_in' => 'Always',
			'record_out' => 'Always',
			'ringtimer' => '0',
			'sipname' => '',
			'tech' => 'sip',
			'type' => 'setup',
			'vm' => 'disabled'
		);
		
		$fields_string = '';
		foreach($var as $key=>$value) {
			$fields_string .= $key . '=' . urlencode($value) .'&'; 
		}
		
		$fields_string = rtrim($fields_string, '&') ; 
		
		echo $fields_string;
		// print_r($var);
		
		$url = "http://192.168.2.11/admin/config.php";
		// $url = "http://192.168.19.128/admin/config.php";
		$url = "http://192.168.3.11/admin/config.php";
		// $url = "http://10.8.3.1:85/admin/config.php";
		
		$this->_curl_post($url, $fields_string);
	}
	
	function _curl_post($url, $vars) {   
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_HEADER, 0);    
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);      
	    curl_setopt($ch, CURLOPT_URL, $url);     
	    curl_setopt($ch, CURLOPT_POST, 1);     
	    curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);     
	    $data = curl_exec($ch);
	    curl_close($ch);

	    echo $data;
	}	

	function f($controller, $request) {
		$to = newdb("aa");
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s";
		$sql = sprintf($fmt, $this->tbl);
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$this->f_exten($to, $row);			
			
		}		
		
		return true;
	}
	
	function f_exten($db, $row) {		
		$fmt = "SELECT * FROM %s WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $row['id']);
		$result = $db->query($sql);
		if ($db->num_rows($result) > 0) {
			return true;
		}
		
		$fmt = "insert into fy.emp_exten values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
		$sql = sprintf($fmt, $row['id'], $row['emp'], $row['exten'], $row['cf'], $row['record_in'], $row['record_out'], $row['out'], $row['orderby'], $row['content'], $row['status'], $row['createtime'], $row['modifytime']);
		echo $sql . "\n";
		$db->query($sql);
		
		return false;
	}
	
	function time($controller, $request) {
		$t1 = "08:02";
		$t2 = "12:00";
		
		$a = strtotime($t1);
		$b = strtotime($t2);
		
		$t = time();
		
		// echo date("Y-m-d H:i", $t);
		
		if ($t > $a && $t < $b) {
			echo "OK";
		} else {
			echo "2222";
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function _emp_by_exten($s) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE exten = '%s'";
		$sql = sprintf($fmt, $this->tbl, $s);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			$row = $this->_view_t($row);
			
			return $row;
		}
		
		return array();
	}
	
	function view_emp($controller, $request) {
		$this->pretreat($controller);
	
		$id = $request['id'];
	
		$ret = $this->_list_emp($id);
	
		$controller->assign_by_ref('result', $ret);
	
		$controller->display($request, 'emp/exten/_list');
		return true;
	}
}

function sip_log($s, $file) {
	$fd = @fopen($file, "a+");
	@fwrite($fd, date("r") . " - ");
	@fwrite($fd, $s . "\n");
	@fclose($fd);
}

function newchannel($self, $data) {
	// echo $self . " aaa \n";
	sip_log(print_r($data, true), "/home/sunxy/sip.log");
}

function aabb($self, $data) {
	// echo $self . " aaa \n";
	print_r($data);
}

function ast_status($self, $data, $server, $port) {
	if (_is_hangup($data)) {
		$t = array('server'=>$server, 'username'=>'admin', 'secret'=>'amp111');
		$am = new AGI_AsteriskManager(NULL, $t);
		$am->connect();
		sleep(5);
		
		$am->Hangup($data['Channel']);		
		$am->disconnect();
		
		sip_log(print_r($data, true), "/home/sunxy/sip.log");
	}
}

function ast_link($self, $data, $server, $port) {
	if (_zap($data)) {
		$t = array('server'=>$server, 'username'=>'admin', 'secret'=>'amp111');
		$am = new AGI_AsteriskManager(NULL, $t);
		$am->connect();
		sleep(5);
		
		$am->Hangup($data['Channel']);		
		$am->disconnect();
		
		sip_log(print_r($data, true), "/home/sunxy/sip.log");
	}
	
	// echo sprintf("server = %s, port = %s\n", $server, $post);
	// echo $self . " bbb \n";	
}

function _zap($r) {
	// if (preg_match('/^SIP\/6595/', $r['Channel1']) && preg_match('/^Zap\//', $r['Channel2'])) {
	if (preg_match('/^Zap\//', $r['Channel1']) && preg_match('/^Zap\//', $r['Channel2'])) {
		sip_log("333", "/home/sunxy/sip.log");
		return true;
	}
	
	sip_log("222", "/home/sunxy/sip.log");
	
	return false;
}

function _is_hangup($r) {
	$channel = $r['Channel'];
	$state = $r['State'];
	
	if ($state <> 'Up') {
		echo sprintf("channel = %s, state = %s\n", $channel, $state);
		return false;
	}	
	
	if (!array_key_exists("Link", $r)) {
		print_r($r);
		return false;
	}
	
	echo sprintf("channel = %s, state = %s\n", $channel, $state);
	$link = $r['Link'];	
	if (preg_match('/^Zap\//', $channel) && preg_match('/^Zap\//', $link)) {
		// sip_log("333", "/home/sunxy/sip.log");
		return true;
	}
	
	// sip_log("222", "/home/sunxy/sip.log");
	
	return false;
}
?>
